/*
 * Copyright 2021 Hannes Dorfmann.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.hannesdorfmann.mosby3.sample.mvi.slice;

import com.hannesdorfmann.mosby3.sample.mvi.MainAbility;
import com.hannesdorfmann.mosby3.sample.mvi.MyApplication;
import com.hannesdorfmann.mosby3.sample.mvi.ResourceTable;
import com.hannesdorfmann.mosby3.sample.mvi.businesslogic.model.MainMenuItem;
import com.hannesdorfmann.mosby3.sample.mvi.dependencyinjection.DependencyInjection;
import com.hannesdorfmann.mosby3.sample.mvi.view.category.CategoryFraction;
import com.hannesdorfmann.mosby3.sample.mvi.view.checkoutbutton.CheckoutButton;
import com.hannesdorfmann.mosby3.sample.mvi.view.home.HomeFraction;
import com.hannesdorfmann.mosby3.sample.mvi.view.menu.MainMenuLayout;
import com.hannesdorfmann.mosby3.sample.mvi.view.menu.MenuViewState;
import com.hannesdorfmann.mosby3.sample.mvi.view.search.SearchFraction;
import com.hannesdorfmann.mosby3.sample.mvi.view.selectedcounttoolbar.SelectedCountToolbar;
import com.hannesdorfmann.mosby3.sample.mvi.view.shoppingcartlabel.ShoppingCartLabel;
import com.hannesdorfmann.mosby3.sample.mvi.view.shoppingcartoverview.ShoppingCartOverviewFraction;
import io.reactivex.disposables.Disposable;
import io.reactivex.subjects.PublishSubject;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.app.Context;

public class MainAbilitySlice extends AbilitySlice {

    private static final String KEY_TOOLBAR_TITLE = "toolbarTitle";

    SlideDrawer drawer;
    MainMenuLayout mainMenu;
    DirectionalLayout titlebar;
    Image imMenu, imSearch;
    Text title;

    DependentLayout bottomBar;
    StackLayout visibleSwipeArea;
    CheckoutButton checkoutButton;
    ShoppingCartLabel shoppingCartLabel;
    SelectedCountToolbar selectedCountToolbar;
    Text mTBottom;

    private Disposable disposable;
    private String titleStr;
    private PublishSubject<Boolean> clearSelectionRelay;
    boolean isDrawerOpen;
    Context context;

    SearchFraction mSearchFraction;
    StackLayout shoppingCartFragment;
    ShoppingCartOverviewFraction mShoppingCartOverviewFraction;
    Fraction mCurrentFraction;
    boolean loadAgin;


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        context = this;
        super.setUIContent(ResourceTable.Layout_ability_main);

        drawer = (SlideDrawer) findComponentById(ResourceTable.Id_drawer);
        mainMenu = (MainMenuLayout) findComponentById(ResourceTable.Id_mainMenu);
        mainMenu.setmComponetContext(this);
        mainMenu.setVisibility(Component.HIDE);


        shoppingCartFragment = (StackLayout) findComponentById(ResourceTable.Id_shoppingCartFragment);
        shoppingCartFragment.setVisibility(Component.HIDE);
        mShoppingCartOverviewFraction = new ShoppingCartOverviewFraction(context);
        ((MainAbility)getAbility()).getFractionManager()
                .startFractionScheduler()
                .add(ResourceTable.Id_shoppingCartFragment, mShoppingCartOverviewFraction, ShoppingCartOverviewFraction.class.getSimpleName())
                .pushIntoStack("shopCart")
                .submit();

        mTBottom = (Text) findComponentById(ResourceTable.Id_mTBottom);
        mTBottom.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if(mCurrentFraction != null && mCurrentFraction instanceof SearchFraction){
                    return;
                }
                if(shoppingCartFragment.getVisibility() == Component.VISIBLE){
                    shoppingCartFragment.setVisibility(Component.HIDE);
                }else{
                    clearSelectionRelay.onNext(true);

                    shoppingCartFragment.setVisibility(Component.VISIBLE);
                    mCurrentFraction = mShoppingCartOverviewFraction;
                }
            }
        });



        titlebar = (DirectionalLayout) findComponentById(ResourceTable.Id_titlebar);
        imMenu = (Image) findComponentById(ResourceTable.Id_imMenu);
        imSearch = (Image) findComponentById(ResourceTable.Id_imSearch);
        title = (Text) findComponentById(ResourceTable.Id_title);
        titlebar.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                closeDrawerIfOpen();
                mSearchFraction = new SearchFraction(context);
                mCurrentFraction = mSearchFraction;
                ((MainAbility)getAbility()).getFractionManager()
                        .startFractionScheduler()
                        .replace(ResourceTable.Id_fragmentContainer, mSearchFraction)
                        .pushIntoStack("Search")
                        .submit();
            }
        });

        imMenu.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if(mainMenu.getVisibility() == Component.HIDE){
                    mainMenu.setVisibility(Component.VISIBLE);
                }else{
                    mainMenu.setVisibility(Component.HIDE);
                }
            }
        });


        drawer.addSlideListener(new SlideDrawer.SlideListener(){
            @Override
            public void onOpen(SlideDrawer slideDrawer, SlideDrawer.SlideDirection slideDirection) {
                isDrawerOpen = true;
            }

            @Override
            public void onMiddle(SlideDrawer slideDrawer, SlideDrawer.SlideDirection slideDirection, SlideDrawer.DrawerState drawerState) {

            }

            @Override
            public void onClose(SlideDrawer slideDrawer, SlideDrawer.SlideDirection slideDirection) {
                isDrawerOpen = false;
            }

            @Override
            public void onSlideChange(SlideDrawer slideDrawer, SlideDrawer.SlideDirection slideDirection, int leftOffset, int topOffset) {

            }
        });
        showCategoryItems(MainMenuItem.HOME);

        // TODO Create a Presenter & ViewState for this Ability
        DependencyInjection dependencyInjection = MyApplication.getDependencyInjection(this);
        disposable = dependencyInjection.getMainMenuPresenter()
                .getViewStateObservable()
                .filter(state -> state instanceof MenuViewState.DataState)
                .cast(MenuViewState.DataState.class)
                .map(this::findSelectedMenuItem)
                .subscribe(this::showCategoryItems);
        clearSelectionRelay = dependencyInjection.getClearSelectionRelay();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        disposable.dispose();
        System.err.println("-------Destroyed -------");
    }
    private String findSelectedMenuItem(MenuViewState.DataState state) {
        for (MainMenuItem item : state.getCategories())
            if (item.isSelected()) return item.getName();

        throw new IllegalStateException("No category is selected in Main Menu" + state);
    }

    @Override
    protected void onBackPressed() {
        if (!closeDrawerIfOpen()) {
            if(mCurrentFraction != null){
                if(mCurrentFraction instanceof SearchFraction){
                    ((MainAbility)getAbility()).getFractionManager().popFromStack();
                    mCurrentFraction = null;
                    return;
                }
                if(shoppingCartFragment.getVisibility() ==  Component.VISIBLE){
                    shoppingCartFragment.setVisibility(Component.HIDE);
                    mCurrentFraction = null;
                    return;
                }
            }
            super.onBackPressed();
        }
    }

    private boolean closeSlidingUpPanelIfOpen() {
        return false;
    }

    private boolean closeDrawerIfOpen() {
        //TODO　DrawSlider暂时替代方案
        if(mainMenu.getVisibility() == Component.VISIBLE){
            mainMenu.setVisibility(Component.HIDE);
            return true;
        }

        return false;
    }

    public void showCategoryItems(String categoryName) {
        closeDrawerIfOpen();

        String currentCategory = title.getText().toString();
        if (!currentCategory.equals(categoryName)) {
            title.setText(categoryName);
            Fraction f;
            if (categoryName.equals(MainMenuItem.HOME)) {
                f = new HomeFraction(this);
            } else {
                f = CategoryFraction.newInstance(categoryName, this);
            }
            mCurrentFraction = f;
            ((MainAbility) getAbility()).getFractionManager().startFractionScheduler().add(ResourceTable.Id_fragmentContainer, f, f.getClass().getSimpleName()).submit();
        }
    }


}
